﻿using dotnet_graphql_demo.Model;
using HotChocolate;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace dotnet_graphql_demo.Infrastructure.Graphql
{
    public class OwnerQuery
    {
        public async Task<List<OwnerOutput>> GetAllOwners([Service] IOwnerRepository ownerRepository,
            [Service] IAccountRepository accountRepository)
        {
            List<Account> accounts = await accountRepository.GetAccountsAllAsync();

            List<Owner> owners = await ownerRepository.GetOwnersAllAsync();
            owners?.ForEach(o => { o.Accounts = accounts.Where((c) => c.OwnerId == o.Id).ToList(); });
            return owners.Adapt<List<OwnerOutput>>();
        }

        public async Task<ResponseData<List<OwnerOutput>>> GetOwners([Service] IOwnerRepository ownerRepository,
            [Service] IAccountRepository accountRepository)
        {
            List<OwnerOutput> ownerOutputs = new List<OwnerOutput>();
            List<Account> accounts = await accountRepository.GetAccountsAllAsync();

            List<Owner> owners = await ownerRepository.GetOwnersAllAsync();
            owners?.ForEach(o => { o.Accounts = accounts.Where((c) => c.OwnerId == o.Id).ToList(); });

            ownerOutputs.AddRange(owners.Adapt<List<OwnerOutput>>());

            return new ResponseData<List<OwnerOutput>>()
            {
                MsgCode = 0,
                Message = "请求成功",
                Obj = ownerOutputs
            };
        }


        public async Task<Owner> GetOwnerAsync(Guid id, OwnerDataLoader dataLoader, CancellationToken cancellationToken)
        {
            return await dataLoader.LoadAsync(id, cancellationToken);
        }

    }
}